package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StopWatch;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
@Transactional
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    private CacheService cacheService;

    /**
     * 未来数据刷新（future->topic）
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {
        //分布式锁：当一个请求进来时，会根据name和UUID来set一个键值，并设置过期时间，如果有其他请求进来会返回null，无法执行此方法
        String lock = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        if(StringUtils.isNotBlank(lock)){
            System.out.println(System.currentTimeMillis() / 1000 + "执行了定时任务");
            // 获取所有未来数据集合的key值
            Set<String> scan = cacheService.scan(ScheduleConstants.FUTURE + "*");
            for (String futureKey : scan) {
                //获取key中的key topic
                String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];
                //获取该组key下当前需要消费的任务数据
                Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                if(!tasks.isEmpty()){
                    //将这些任务数据添加到消费者队列中
                    cacheService.refreshWithPipeline(futureKey,topicKey,tasks);
                    System.out.println("成功的将" + futureKey + "下的当前需要执行的任务数据刷新到" + topicKey + "下");
                }
            }
        }
    }

    /**
     * 数据库数据同步到redis
     */
    @PostConstruct
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData(){
        //清理缓存中的数据
        clearCache();
        //查看小于未来5分钟的所有任务
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);

        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));
        if(taskinfos != null && taskinfos.size() != 0){
            for (Taskinfo taskinfo : taskinfos) {
                //把任务加入redis
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTask(task);
            }
        }
        log.info("数据库的任务同步到了redis");
    }

    private void clearCache() {
        //清理缓存中的数据
        Set<String> futurekeys = cacheService.scan(ScheduleConstants.FUTURE + "*");// future_
        Set<String> topickeys = cacheService.scan(ScheduleConstants.TOPIC + "*");// topic_
        cacheService.delete(futurekeys);
        cacheService.delete(topickeys);
    }

    /**
     * 添加延迟任务
     *
     * @param task
     * @return
     */
    @Override
    public long addTask(Task task) {
        //1，添加任务到数据库
        boolean flag = addTaskDb(task);
        //2，添加任务到redis
        if (flag) {
            addTaskToCache(task);
        }
        return task.getTaskId();
    }

    /**
     * 取消延迟任务
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean deleteTask(long taskId) {
        boolean flag = false;
        //删除任务
        Task task = updateTask(taskId, ScheduleConstants.CANCELLED);
        if (task != null) {
            cacheRemoveTask(task);
            flag = true;
        }
        return flag;
    }

    /**
     * 按照类型和优先级消费数据
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        Task task = null;
        try {
            //从redis中拉取数据
            String key = type + "_" + priority;
            String json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if (StringUtils.isNotBlank(json)) {
                task = JSON.parseObject(json, Task.class);
                //修改数据库信息
                updateTask(task.getTaskId(), ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {
            log.error("poll task exception");
            e.printStackTrace();
        }
        return task;
    }

    /**
     * 从redis中删除任务
     *
     * @param task
     */
    private void cacheRemoveTask(Task task) {
        //1,获取key
        String key = task.getTaskType() + "_" + task.getPriority();
        //2,如果任务的执行时间小于当前时间，从list中删除
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
        } else {
            //3,如果任务的执行时间大于当前时间，从zset中删除
            cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
        }
    }

    /**
     * 删除，更新任务日志
     *
     * @param taskId
     * @param status
     * @return
     */
    private Task updateTask(long taskId, int status) {
        Task task = null;
        try {
            //删除任务信息
            taskinfoMapper.deleteById(taskId);

            //更新任务日志
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            //获取task
            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs, task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (BeansException e) {
            e.printStackTrace();
            log.info("修改任务状态失败,taskId为{}", taskId);
        }
        return task;
    }

    /**
     * 添加任务到redis
     *
     * @param task
     */
    private void addTaskToCache(Task task) {
        //1,获取key
        String key = task.getTaskType() + "_" + task.getPriority();
        //2,获取五分钟后的毫秒值
        Calendar instance = Calendar.getInstance();
        instance.add(instance.MINUTE, 5);
        long nextScheduleTime = instance.getTimeInMillis();
        //3,如果任务的执行时间小于当前时间，存入list
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        } else if (task.getExecuteTime() <= nextScheduleTime) {
            //4,如果任务的执行时间大于当前时间&&小于预设时间（未来5分钟），存入zset
            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }
    }

    /**
     * 添加任务到数据库
     *
     * @param task
     * @return
     */
    private boolean addTaskDb(Task task) {
        boolean flag = false;
        try {
            //添加taskInfo（任务表）
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //设置taskID
            task.setTaskId(taskinfo.getTaskId());

            //添加taskInfoLog（任务日志表）
            TaskinfoLogs logs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, log);
            logs.setVersion(1);
            logs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(logs);
            flag = true;
        } catch (BeansException e) {
            e.printStackTrace();
        }
        return flag;
    }
}
